var googleCalendar = require('../../modules/morning/gcalendar.js');
var https = require('https');


exports.authenticationGoogle = function(req, res){

    if(googleCalendar.access_token == null)
    {

    if(!req.query.code){

      //Redirect the user to Google's authentication form 
      googleCalendar.google_calendar.getGoogleAuthorizeTokenURL(function(err, redirecUrl) {
        if(err) return res.send(500,err);
      return res.redirect(redirecUrl);
    });

    }else{
      //Get access_token from the code
      googleCalendar.google_calendar.getGoogleAccessToken(req.query, function(err, access_token, refresh_token) {

        if(err) return res.send(500,err);

        googleCalendar.setTokens(access_token, refresh_token); // set tokens


      
        console.log('Logged user with google calendar (access_token:'+access_token+', refresh_token:'+refresh_token+').');

        return res.redirect('/calendar');
    });
    }

    }
    else // authentication OK
    {
      res.end('Already authentified with google calendar !');
    }
};


exports.printCalendar = function(req, res)
{

    googleCalendar.getTodayEvents(null, function(err, text)
    {
        if(err == false)
            res.end(text);
        else
        {
            res.redirect('/authenticationGoogle');
            console.log('Redirecting to /authenticationGoogle');
        }
    });

  /**

    if(googleCalendar.access_token == null)
    {
        res.redirect('/authenticationGoogle');
    }
    else
    {

        var parameters = {
            access_token: googleCalendar.access_token,
            key: '303778581537-jlnj2fscgs59u07adioivvbstfrg1g74.apps.googleusercontent.com'
        };

        var options = {
            query: parameters
        };

        restler.get('https://www.googleapis.com/calendar/v3/users/me/calendarList', options).on('complete', function(result)
        {
            console.log('PASSAGE FONCTION');
            if(result['items'])
            {
                console.log('got calendar list');
                var l = result['items'].length;
                var calendar = null;

                for(var i = 0; i < l; i++)
                {
                    if(result['items'][i]['summary'] == 'GHOME')
                        calendar = result['items'][i];
                }

                if(calendar)
                {
                    resler.get('https://www.googleapis.com/calendar/v3/calendars/'+encodeURIComponent(calendar['id'])+'/events').on('complete', function(ythg){}); function(r)
                    {
                        if(result['items'])
                        {
                            var l = result['items'].length;
                            var text = '';

                            for(var i = 0; i < l; i++)
                            {
                                text += result['items'][i]['summary']+', ';
                            }

                            res.end(text);
                        }
                        else
                            res.end('Could not load events list.');
                    });
                    res.end(calendar['summary']);
                }
                else
                    res.end('Could not find calendar named "GHOME"');
            }
            else
                res.end('Could not load calendar list.\n\n'+JSON.stringify(result));
        });

    }



  googleCalendar.google_calendar.listCalendarList(googleCalendar.access_token, function(err, calendarList) {

      if(err == null || Object.keys(err).length == 0)
      {

        //if(Object.keys(err).length == 0)
        //calendarList = JSON.parse(calendarList); // débuggage bizarre au cas où le JSON n'est pas déjà parsé. Cela semble arriver quand err n'est pas null mais un objet vide...


        if(calendarList['items'])
        {

        var l = calendarList['items'].length;

        var texte = "";

      for(var i = 0; i < l; i++)
      {
        var calendar = calendarList.items[i];

        if(calendar.summary == 'GHOME')
        {
        
          //Events.list

          var timeMin = new Date();
          timeMin.setHours(0);
          timeMin.setMinutes(0);

          var timeMax = new Date();
          timeMax.setHours(23);
          timeMax.setMinutes(59);

          var options = {'timeMin': timeMin.toISOString(), 'timeMax': timeMax.toISOString()};
          
          googleCalendar.google_calendar.listEvent(googleCalendar.access_token, calendar.id, function(err, events) {
            if(err != null || events == undefined)
            {
              texte = 'Cannot read events of calendar "GHOME".';
            }
            else
            {
              texte = 'Salut beau gosse, voici ton emploi du temps du jour : '
              for(var j = 0; j < events.items.length; j++) {
                var date = new Date(events.items[j].start.dateTime);
                if(date >= timeMin && date <= timeMax)
                {
                  texte += date.getHours() + ' heures ' + events.items[j].summary + ', ';
                }
              }
              texte += '. Amuses toi bien, bonne journée !';
            }

            say.speak('Audrey', texte);
            res.end(texte);
          });


  //res.end(calendar.id);

        }

      
      }

        
        
    }
    else
    {
      res.end('Items does not exist.\n\nResponse:\n\n'+JSON.stringify(calendarList));
    }

    }
    else
    {
      res.redirect('/authenticationGoogle');
      console.log('Could not connect to google calendar, redirecting to authentication page (err:'+JSON.stringify(err)+',calendarList:'+calendarList+').');
    }

  });

**/

}

